<template>
	<view class="lease-order-lists">
		<!-- Tabs -->
		<view class="tabs-container">
			<u-tabs :list="tabs" :is-scroll="false" :current="tabCurrent" font-size="28" active-color="#333333"
				bar-width="80" :bar-style="{'background-color': '#24A3FF'}" @change="changeTab" />
		</view>

		<!-- List Content -->
		<view class="main">
			<block v-for="(item, index) in lists" :key="item.id">
				<view class="order-item">
					<view class="order-header">
						<view class="lighter">订单号：{{item.order_sn}}
							<image @tap.stop="toCopy(item.order_sn)" src="../../static/images/copy_icon.png"
								mode="widthFix" style="width: 30rpx;margin-left: 10rpx;">
							</image>
						</view>
						<view :style="{color:getStatusColor(item.order_status)}">
							{{ item.status_name }}
						</view>
					</view>

					<view class="order-content">
						<view class="row" style="gap:20rpx">
							<image :src="item.image" mode="aspectFill" style="width:140rpx;height: 140rpx;">
							</image>
							<view>
								<view class="black mt10">
									{{item.goods_name}}
								</view>
								<view class="mt20 lighter">
									{{item.spec_value}}
								</view>
							</view>
						</view>
						<view class="mt20" v-if="[1,2,3,4].includes(item.order_status)"
							style="padding:20rpx;background-color: #f5f9fa;">
							<view v-if="item.order_status == 1">
								<text class="muted">取货地址：</text>
								{{item.name}}
							</view>
							<view v-else-if="item.order_status == 2" class="row-between flex1">
								<view v-if="item.delivery_type==1">
									<text class="muted">发货时间：</text>
									{{item.pt_fa.add_day}}
								</view>
								<view>
									<text class="muted">租期共：</text>
									{{item.goods_info}}
								</view>
							</view>
							<view v-else-if="item.order_status ==3" class="row-between flex1">
								<view v-if="item.countdown.status == 1">
									<text class="muted">剩余时间：</text>
									<u-count-down :timestamp="item.countdown.now_time" bg-color="transparent"
										separator="zh"></u-count-down>
								</view>
								<view v-else>
									<text class="muted">超出时间：</text>
									{{item.countdown.differ}}
								</view>
								<view>
									<text class="muted">租期共：</text>
									{{item.goods_info}}
								</view>
							</view>
							<view v-else class="row-between flex1">
								<view>
									<text class="muted">归还时间：</text>
									{{item.expire_day}}
								</view>
								<view>
									<text class="muted">租期共：</text>
									{{item.goods_info}}
								</view>
							</view>
							<view v-if="item.order_status == 3 && item.countdown.status==2" class="row-between flex1">
								<view style="color: #ff2100;">
									您的订单已超时，将按照原租金的1.5倍计算租金
								</view>
							</view>
							<view v-if="item.ya_amount" class="row-between mt10 flex1">
								<view class="row">
									<view class="muted">
										押金
										<u-icon name="question-circle" @click="openPriceModal(item.ya_amount)"></u-icon>
										：
									</view>
									￥{{item.ya_amount.money}}
								</view>
								<view>
									<text class="muted">运费：</text>
									￥{{item.ya_amount.shipping_price}}
								</view>
							</view>
						</view>
					</view>
					<!-- Button -->
					<view class="order-footer">
						<block v-for="subIndex in getButtons(item)" :key="subIndex">
							<view class="order-button" :class="[buttonList[subIndex]['class']]"
								@tap="onOrderButton(buttonList[subIndex].key, lists[index])">
								{{ buttonList[subIndex].name }}
							</view>
						</block>
					</view>
				</view>
			</block>
		</view>

		<!-- Footer -->
		<view>
			<loading-footer :status="status" />
		</view>

		<!-- Widget -->
		<view>
			<!-- 取消订单 -->
			<u-modal v-model="showCloseOrderModal" content="取消订单" :show-cancel-button="true"
				@confirm="handleOrderClose" />

			<!-- 删除订单 -->
			<u-modal v-model="showDelOrderModal" content="删除订单" :show-cancel-button="true" @confirm="handleOrderDel" />

			<!-- 确认收货 -->
			<u-modal v-model="showConfirmOrderModal" content="确认收货" :show-cancel-button="true"
				@confirm="handleOrderConfirm" />

			<u-modal v-model="showPriceModal" title="费用说明">
				<view style="padding: 20rpx;">
					<view class="row-between">
						<view>押金：</view>
						<view>￥{{priceModalInfo.money}}</view>
					</view>
					<view v-if="priceModalInfo.hj_money>0" class="row-between mt20">
						<view>还机支付：</view>
						<view>-￥{{priceModalInfo.hj_money}}</view>
					</view>
					<view v-if="priceModalInfo.pt_money>0" class="row-between mt20">
						<view>平台定损：</view>
						<view>-￥{{priceModalInfo.pt_money}}</view>
					</view>
					<view v-if="priceModalInfo.order_money>0" class="row-between mt20">
						<view>转永久租赁支付：</view>
						<view>-￥{{priceModalInfo.order_money}}</view>
					</view>
					<view class="row-between mt20">
						<view>可退还金额：</view>
						<view>￥{{priceModalInfo.yu_money}}</view>
					</view>
				</view>
			</u-modal>

			<!-- 续租 -->
			<u-popup v-model="showReletOrderPopup" mode="center" border-radius="20">
				<view class="relet">
					<view class="relet-title">续租</view>
					<view class="relet-content">
						<view class="relet-label">请选择租期</view>
						<view class="relet-list">
							<block v-for="item in reletList" :key="item.periods_id">
								<view class="relet-item" :class="{'relet-item--active': relet == item.periods_id}"
									@tap="relet = item.periods_id">
									{{ item.name }}
								</view>
							</block>
						</view>
					</view>
					<view class="relet-widget">
						<view class="relet-cancel" @tap="showReletOrderPopup = false">取消</view>
						<view class="relet-confirm" @tap="handleRelet">确认</view>
					</view>
				</view>
			</u-popup>

			<!-- 还机 -->
			<u-popup v-model="showReturnOrderPopup" mode="center" border-radius="20">
				<view class="return">
					<view class="return-title">温馨提示</view>
					<view class="return-content">您当前租期未到期，提前还机需支付相应的违约金，是否确认还机？</view>
					<view class="return-widget">
						<view class="return-cancel" @tap="showReturnOrderPopup = false">取消</view>
						<view class="return-confirm" @tap="goReturnOrder">确认</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>


<script>
	import {
		getLeaseOrderList, // 订单列表
		getUserLeaseOrder, //新-订单列表
		leaseOrderCancel, // 取消订单
		leaseOrderDel, // 删除订单
		leaseOrderConfirm, // 确认收货
		leaseOrderRelet, // 续租
		leaseReturnCheck, // 还机验证
	} from '@/api/lease.js';
	import {
		prepay,
		getAlipayPayStatus
	} from '@/api/app';
	import {
		wxpay,
		alipay
	} from '@/utils/pay'
	import {
		loadingType
	} from '@/utils/type';
	import {
		loadingFun,
		copy
	} from "@/utils/tools";

	export default {
		data() {
			return {
				showDelOrderModal: false, // 删除订单Modal
				showCloseOrderModal: false, // 取消订单Modal
				showConfirmOrderModal: false, // 确认收货Modal
				showReletOrderPopup: false, // 续租 Popup
				showReturnOrderPopup: false, // 还机 Popup
				reletList: [], // 续租期 数据列表
				relet: '', // 选择的租期
				currentActiveID: '', // 当前选中的订单ID
				showPriceModal: false, //金额详情弹窗
				priceModalInfo: null, //弹窗info
				// Tabs列表
				tabs: [{
					key: 0,
					name: '全部'
				}, {
					key: 1,
					name: '配送/发货'
				}, {
					key: 2,
					name: '核销/收货'
				}, {
					key: 3,
					name: '租用中'
				}, {
					key: 4,
					name: '已完成'
				}],
				tabCurrent: 0, // 当前Tab索引  [0-全部; 1-待付款; 2-待收货; 3-租用中; 4-已完成;]
				lists: [], // 当前订单数据列表 
				page: 1, // 当前页数状态
				status: loadingType.LOADING, // 当前加载状态
				// 订单状态映射表

				// 按钮列表
				buttonList: {
					0: {
						key: 'pay',
						name: '立即付款',
						class: 'order-button--active'
					},
					1: {
						key: 'repayment',
						name: '去还款',
						class: 'order-button--active'
					},
					2: {
						key: 'receive',
						name: '确认收货',
						class: 'order-button--normal'
					},
					3: {
						key: 'evaluate',
						name: '去评价',
						class: 'order-button--normal'
					},
					4: {
						key: 'return',
						name: '还机',
						class: 'order-button--normal'
					},
					5: {
						key: 'buy',
						name: '买断',
						class: 'order-button--normal'
					},
					6: {
						key: 'buy_detail',
						name: '买断详情',
						class: 'order-button--normal'
					},
					7: {
						key: 'return_detail',
						name: '还机详情',
						class: 'order-button--normal'
					},
					8: {
						key: 'relet',
						name: '续租',
						class: 'order-button--normal'
					},
					9: {
						key: 'close',
						name: '取消订单',
						class: 'order-button--inactive'
					},
					10: {
						key: 'express',
						name: '查看物流',
						class: 'order-button--inactive'
					},
					11: {
						key: 'del',
						name: '删除订单',
						class: 'order-button--inactive'
					},
					12: {
						key: 'contract',
						name: '上传合同',
						class: 'order-button--normal'
					},
					13: {
						key: 'writeOff',
						name: '去核销',
						class: 'order-button--normal'
					}
				}
			}
		},

		methods: {
			openPriceModal(item) {
				this.showPriceModal = true;
				this.priceModalInfo = item;
			},
			toCopy(str) {
				copy(str);
			},
			getStatusColor(status) {
				if (status == 3) {
					return '#999999'
				} else {
					return '#e26d60'
				}
			},
			// 切换Tabs
			changeTab(index) {
				this.tabCurrent = index;
			},

			// 输出分期单位
			getPeriodsUnit(value) {
				switch (value) {
					case 'is_week':
						return '周';
					case 'is_month':
						return '个月';
				}
			},

			// 每天多少钱
			oneDayPrice(unit, issueRent) {
				switch (unit) {
					case 'is_week':
						return Number((issueRent / 7).toString().match(/^\d+(?:\.\d{0,2})?/));
					case 'is_month':
						return Number((issueRent / 30).toString().match(/^\d+(?:\.\d{0,2})?/));
				}
			},

			// 获取该订单应有的按钮
			getButtons(order) {
				/**
				 * order_status （订单状态;0-待付款;1-待发货/取货/配送;2-待收货;3-租用中;4-已完成;5-已关闭,6归还待确认,7续租待支付）
					delivery_type（配送方式;1-快递发货;2-上门自提;3-同城配送）
					type_status（状态，1租赁，2买断,3预约订单）
				 */
				const order_status = order.order_status,
					delivery_type = order.delivery_type,
					type_status = order.type_status;0
				if (order_status == 0) {
					return [0, 9];
				} else if (order_status == 1) {
					// return [9]
				} else if (order_status == 2) {
					if (delivery_type == 1) {
						return [2]
					} else if (delivery_type == 2) {
						// return [9, 13]
						return [13]
					} else if (delivery_type == 3) {
						return [13]
					}
				}
				return;
				// 以下流程目前弃用
				// console.log(order);
				switch (status) {
					// 待付款
					case 0:
						return [0, 9];
						// 待发货
					case 1:
						return [9];
						// 待收货
					case 2:
						return [2, 10];
						// 租用中
					case 3: {
						const btns = [5, 8];
						// 支付
						if (order.is_repayment * 1) btns.push(1);
						// 还机
						if (!order.is_return_details_show * 1 && order.is_return_show * 1) btns.unshift(4);
						// 还机详情
						if (order.is_return_details_show * 1) return [7];
						// 买断
						if (order.is_buyout_details_show * 1) btns.unshift(6);

						return btns;
					}
					// 已完成
					case 4: {
						const btns = [];
						// 评价
						if (!order?.lease_order_goods[0]?.is_comment * 1) btns.push(3);
						// 还机详情
						if (order.is_return_details_show * 1) btns.unshift(7);
						// 买断详情
						if (order.is_buyout_details_show * 1) btns.unshift(6);
						return btns;
					}
					// 已关闭
					case 5:
						return [11];
				}
			},

			// 订单按钮
			onOrderButton(event, order) {
				this.currentActiveID = order.id;
				switch (event) {
					// 立即付款
					case 'pay':
						return this.onOrderPay(order);
						// 去还款
					case 'repayment':
						return this.onOrderRepayment();
						// 确认收货
					case 'receive':
						return this.onOrderReceive();
						// 去评价
					case 'evaluate':
						return this.onOrderEvaluate(order);
						// 还机
					case 'return':
						return this.onOrderReturn();
						// 买断
					case 'buy':
						return this.onOrderBuy();
						// 买断详情
					case 'buy_detail':
						return this.onOrderBuyDetail();
						// 还机详情
					case 'return_detail':
						return this.onOrderReturnDetail();
						// 续租
					case 'relet':
						return this.onOrderRelet();
						// 取消订单
					case 'close':
						return this.onOrderClose();
						// 查看物流
					case 'express':
						return this.onOrderExpress();
						// 删除订单
					case 'del':
						return this.onOrderDel();
						// 合同
					case 'contract':
						return this.onContract();
					case 'writeOff':
						return this.toWriteOff();
				}
			},
			toWriteOff() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/to_write_off/to_write_off?id=${id}`
				})
			},
			// 点击合同
			onContract() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/lease_contract/lease_contract?id=${id}`
				})
			},

			// 按下立即付款按钮
			onOrderPay(order) {
				const payWay = order.pay_way;
				const id = this.currentActiveID;

				prepay({
					from: 'lease_order',
					order_id: id
				}).then(res => {
					const code = res.code;
					const data = res.data;

					switch (code) {
						// 微信支付
						case 1:
							return this.handlePayWeChat(data, id);
							// 支付宝支付
						case 20001:
							return this.handlePayAlipay(data, id);
							// 余额支付
						case 10001:
							return;
					}
				});
			},

			// 按下去还款按钮
			onOrderRepayment() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/lease_bill/lease_bill?id=${id}`
				})
			},

			// 按下确认收货按钮
			onOrderReceive() {
				this.showConfirmOrderModal = true;
			},

			// 按下去评价按钮
			onOrderEvaluate(order) {
				const id = this.currentActiveID;
				const goodsID = order?.lease_order_goods[0]?.id;
				uni.navigateTo({
					url: `/bundle/pages/lease_goods_reviews/lease_goods_reviews?id=${id}&goods_id=${goodsID}`
				})
			},

			// 按下还机按钮
			onOrderReturn() {
				const id = this.currentActiveID;
				leaseReturnCheck({
					id,
					action: 'check'
				}).then(res => {
					const code = res.code;
					console.log(res);
					if (code == 1) {
						uni.navigateTo({
							// url: `/bundle/pages/lease_return_detail/lease_return_detail?id=${id}`
							url: `/bundle/pages/lease_return_express/lease_return_express?id=${id}`
						})
					} else {
						this.showReturnOrderPopup = true;
					}
				})
			},

			// 按下买断按钮
			onOrderBuy() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/lease_pay_buy/lease_pay_buy?id=${id}`
				})
			},

			// 按下买断详情按钮
			onOrderBuyDetail() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/lease_buy_detail/lease_buy_detail?id=${id}`
				})
			},

			// 按下还机详情按钮
			onOrderReturnDetail() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/lease_return_detail/lease_return_detail?id=${id}`
				})
			},

			// 按下续租按钮
			onOrderRelet() {
				uni.showLoading({
					title: '加载中'
				});
				const id = this.currentActiveID;
				leaseOrderRelet({
					id,
					action: 'info'
				}).then(res => {
					uni.hideLoading();
					if (res.code != 1) return;
					this.showReletOrderPopup = true;
					const data = res.data;
					this.reletList = data;
					this.relet = data[0].periods_id;
				});
			},

			// 按下取消订单按钮
			onOrderClose(id) {
				this.showCloseOrderModal = true;
			},

			// 按下查看物流按钮
			onOrderExpress() {
				const id = this.currentActiveID;
				uni.navigateTo({
					url: `/bundle/pages/lease_order_express/lease_order_express?id=${id}`
				})
			},

			// 按下删除订单按钮
			onOrderDel() {
				this.showDelOrderModal = true;
			},


			// 取消订单处理
			handleOrderClose() {
				const id = this.currentActiveID;
				leaseOrderCancel({
					id
				}).then(res => this.handleRefresh());
			},

			// 删除订单处理
			handleOrderDel() {
				const id = this.currentActiveID;
				leaseOrderDel({
					id
				}).then(res => this.handleRefresh());
			},

			// 确认收货处理
			handleOrderConfirm() {
				const id = this.currentActiveID;
				leaseOrderConfirm({
					id
				}).then(res => this.handleRefresh());
			},

			// 续租处理
			handleRelet() {
				const id = this.currentActiveID;

				leaseOrderRelet({
					id,
					periods_id: this.relet,
					action: 'submit',
				}).then(res => {
					this.showReletOrderPopup = false;
					if (res.code != 1) return;
					uni.showToast({
						title: '续租成功',
						icon: 'success'
					});
				});
			},

			// 微信支付
			handlePayWeChat(data, id) {
				wxpay(data).then(res => {
					if (res == 'success') {
						this.handleRefresh();
						uni.navigateTo({
							url: '/bundle/pages/lease_pay_result/lease_pay_result' +
								'?id=' + id
						});
					} else {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
					}
				})
			},

			// 支付宝支付
			handlePayAlipay(data, id) {
				// #ifdef H5
				alipay(data);
				// #endif

				// #ifdef MP-ALIPAY
				const tradeNo = data?.data?.trade_no;
				my.tradePay({
					tradeNO: tradeNo,
					success: (res) => {
						getAlipayPayStatus({
							trade_no: tradeNo
						}).then(res => {
							if (res.tradeStatus == 'TRADE_SUCCESS') {
								uni.redirectTo({
									url: `/bundle/pages/lease_pay_result/lease_pay_result?id=${this.billInfo.id}`
								})
							} else {
								uni.showToast({
									title: '支付失败',
									icon: 'none'
								});
							}
						});
					},
					fail: (res) => {
						console.log(res);
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
					}
				});
				// #endif
			},


			// 查看订单详情
			goOrderDetail(id) {
				uni.navigateTo({
					url: '/bundle/pages/lease_order_detail/lease_order_detail' +
						'?id=' + id
				})
			},

			// 前往还机
			goReturnOrder() {
				const id = this.currentActiveID;
				this.showReturnOrderPopup = false;
				uni.navigateTo({
					url: '/bundle/pages/lease_goods_return/lease_goods_return' +
						'?id=' + id
				})
			},

			// 列表数据请求
			reqLeaseOrderLists(type) {
				loadingFun(
					getUserLeaseOrder,
					this.page,
					this.lists,
					this.status, {
						status: type
					}
				).then(res => {
					if (!res) return;
					this.page = res.page
					this.lists = res.dataList
					this.status = res.status
				});
			},

			// 重置请求状态
			reset() {
				this.lists = [];
				this.page = 1;
				this.status = loadingType.LOADING;
			},

			// 刷新数据
			handleRefresh() {
				// 重置状态
				this.reset();
				// 请求对应tab的列表数据
				const type = this.tabs[this.tabCurrent].key;
				this.reqLeaseOrderLists(type);
			}
		},

		watch: {
			tabCurrent(value) {
				this.handleRefresh();
			}
		},

		onLoad(options) {
			// type: all-全部；pay-待付款；delivery-待收货；renting-租用中；finish-已完成；close-已关闭
			// const type = options.type || 'all';
			// this.reqLeaseOrderLists(type);

			// uni.navigateTo({
			// 	url: '/pages/webview/webview?url=http://192.168.10.88:19009/#/'
			// })
		},

		onPullDownRefresh() {
			uni.stopPullDownRefresh();
			this.handleRefresh();
		},

		onShow() {
			this.handleRefresh();
		},

		// 上拉加载更多
		onReachBottom() {
			const type = this.tabs[this.tabCurrent].key;
			this.reqLeaseOrderLists(type);
		},
	}
</script>


<style scoped>
	.lease-order-lists {
		padding-top: 88rpx;
	}

	.tabs-container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
	}

	.main {
		padding: 20rpx;
	}

	.order-item {
		padding: 0 20rpx;
		border-radius: 10px;
		background-color: #FFFFFF;
	}

	.order-item:nth-child(n+2) {
		margin-top: 20rpx;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 80rpx;
		/* border-bottom: 1px solid #E5E5E5; */
		font-size: 28rpx;
	}

	.order-content {
		padding: 20rpx 0;
	}

	.order-pay {
		padding-top: 20rpx;
		text-align: right;
	}

	.order-pay-lable {
		margin-right: 10rpx;
		font-size: 24rpx;
		color: #999999;
	}

	.order-footer {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		/* height: 100rpx; */
		/* border-top: 1px solid #E5E5E5; */
	}

	.order-button {
		box-sizing: border-box;
		padding: 10rpx 40rpx;
		border-radius: 100px;
		margin-bottom: 30rpx;
		font-size: 26rpx;
	}

	.order-button:nth-child(n+2) {
		margin-left: 20rpx;
	}

	.order-button--active {
		background-color: #24A3FF;
		color: #FFFFFF;
	}

	.order-button--inactive {
		border: 1px solid #D7D7D7;
		background-color: #FFFFFF;
		color: #666666;
	}

	.order-button--normal {
		background-color: #FFFFFF;
		border: 1px solid #24A3FF;
		color: #24A3FF;
	}


	.order-button--error {
		background-color: #FFFFFF;
		border: 1px solid #FF2C3C;
		color: #FF2C3C;
	}

	.relet,
	.return {
		width: 640rpx;
		padding: 30rpx 40rpx;
		background-color: #FFFFFF;
	}

	.relet-title,
	.return-title {
		padding-bottom: 30rpx;
		text-align: center;
		font-weight: 500;
		font-size: 34rpx;
		color: #333333;
	}

	.return-content {
		text-align: center;
		font-size: 32rpx;
		color: #333333;
	}

	.relet-label {
		font-size: 28rpx;
		color: #333333;
	}

	.relet-list {
		display: flex;
		flex-wrap: wrap;
	}

	.relet-item {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 152rpx;
		height: 58rpx;
		margin: 20rpx 20rpx 0 0;
		border-radius: 50px;
		font-size: 26rpx;
		color: #333333;
		background-color: #F4F4F4;
	}

	.relet-item--active {
		background-color: #E8F6FF;
		box-shadow: 0 0 0 1px #24A3FF;
		color: #24A3FF;
	}

	.relet-widget,
	.return-widget {
		display: flex;
		justify-content: space-between;
		margin-top: 84rpx;
	}

	.relet-cancel,
	.relet-confirm,
	.return-cancel,
	.return-confirm {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 268rpx;
		height: 74rpx;
		font-size: 32rpx;
		border-radius: 50px;
	}

	.relet-cancel,
	.return-cancel {
		background-color: #F6F6F6;
		color: #666666;
	}

	.relet-confirm,
	.return-confirm {
		background-color: #24A3FF;
		color: #FFFFFF;
	}
</style>